package com.example.helloworld;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class WinView extends View {
	
	private Movie mMovie;
    private long mMovieStart;

    private static byte[] streamToBytes(InputStream is) {
        ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) >= 0) {
                os.write(buffer, 0, len);
            }
        } catch (java.io.IOException e) {
        }
        return os.toByteArray();
    }

	public WinView(Context context) {
		super(context);
        setFocusable(true);

        this.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        InputStream is;

        is = context.getResources().openRawResource(R.drawable.win1);
        //Why was this put in an if statement if we default it to true?
        
        mMovie = Movie.decodeStream(is);
	}

	public WinView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public WinView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	@SuppressLint("DrawAllocation")
	@Override
	protected void onDraw(Canvas canvas) {
//		// TODO Auto-generated method stub
//		super.onDraw(canvas);
//		Paint p = new Paint();
//		Rect r = canvas.getClipBounds();
//		
//		// Draw a rectangle that takes up the screen and has a you win message
//		p.setTextAlign(Align.CENTER);
//		p.setARGB(192, 0, 255, 0);
//		p.setTextSize(40);
//		
//		canvas.drawText("YOU WIN!", r.centerX(), r.centerY(), p);
//
//		canvas.drawColor(Color.WHITE);
		// Try clearing the view, not sure if this works
		//this.clearAnimation();
		
		//canvas.drawColor(0xFFCCCCCC);            

        Paint p = new Paint();
        p.setAntiAlias(true);

        long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) {   // first time
            mMovieStart = now;
        }
        if (mMovie != null) {
            int dur = mMovie.duration();
            if (dur == 0) {
                dur = 1000;
            }
            int relTime = (int)((now - mMovieStart) % dur);
            mMovie.setTime(relTime);
            mMovie.draw(canvas, (getWidth()/2) - (mMovie.width()/2),0);
            invalidate();
        }
	}

}
